<template>
  <div>
    <div style="margin-bottom: 10px">
    </div>
    <div style="padding: 10px 0">
      <el-input style="width: 200px" suffix-icon="el-icon-search" placeholder="请输入名称" v-model="name"></el-input>
      <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
      <el-button type="warning" @click="reset">重置</el-button>
    </div>
    <div style="padding: 10px 0">
      <el-button type="primary" @click="handleAdd"><i class="el-icon-plus"></i> 新增</el-button>
      <el-button type="danger" @click="isDelBatch"><i class="el-icon-delete"></i> 批量删除</el-button>
    </div>
    <el-table @selection-change="handleSelectionChange" :data="tableData" border stripe
              :cell-style="{'text-align':'center'}"
              :header-cell-style="{background:'#eef1f6',color:'#606266','text-align':'center'}">
      <el-table-column type="selection"></el-table-column>
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="name" label="名称"></el-table-column>
      <el-table-column prop="flag" label="唯一标识"></el-table-column>
      <el-table-column prop="description" label="描述"></el-table-column>
      <el-table-column label="操作" width="300" align="center">
        <template v-slot="scope">
          <el-button type="primary" @click="selectMenu(scope.row)"><i class="el-icon-menu"></i> 分配菜单</el-button>
          <el-button type="success" @click="handleEdit(scope.row)"><i class="el-icon-edit"></i> 编辑</el-button>
          <el-popconfirm class="ml-5" title="确定要删除本条记录吗？"
                         cancel-button-text='我再想想' confirm-button-text='确定'
                         icon="el-icon-info" icon-color="red"
                         @confirm="deleteById(scope.row.id)">
            <el-button type="danger" slot="reference"><i class="el-icon-delete"></i> 删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <div class="pd-10">
      <el-pagination
          :total="total"
          :page-size="pageSize"
          :current-page="pageNum"
          :page-sizes="[5, 10, 15, 20]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange">
      </el-pagination>
    </div>

    <!--编辑用户弹框-->
    <el-dialog title="角色信息" :visible.sync="dialogFormVisible" width="35%">
      <el-form label-width="80px" size="small">
        <el-form-item label="名称">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
    <!--批量删除弹框-->
    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
      <span><i class="el-icon-delete-solid" style="font-size: 35px"></i>  确定要删除这些数据吗？</span>
      <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="delBatch">确 定</el-button>
        </span>
    </el-dialog>
    <!--菜单分配-->
    <el-dialog title="菜单分配" :visible.sync="menuDialogVis" width="30%">
      <el-tree
          :props="props"
          :data="menuData"
          show-checkbox
          node-key="id"
          ref="tree"
          :default-expanded-keys="expends"
          :default-checked-keys="checks">
         <span class="custom-tree-node" slot-scope="{ node, data }">
            <span><i :class="data.icon"></i> {{ data.name }}</span>
         </span>
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="menuDialogVis = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleMenu">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "RoleManage",
  data() {
    return {
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
      name: "",
      dialogFormVisible: false,
      form: {},
      multipleSelection: [],
      dialogVisible: false,
      menuDialogVis: false,
      menuData: [],
      props: {
        label: 'name',
      },
      expends: [],
      checks: [],
      roleId: 0,
      roleFlag: '',
      ids: []
    }
  },
  created() {
    this.load()
  },
  methods: {
    load() {
      this.request.get("/role/page", {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          name: this.name
        }
      }).then(res => {
        this.total = res.data.total
        this.tableData = res.data.records
      })
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum
      this.load()
    },
    reset() {
      this.name = ""
      this.load()
    },
    handleAdd() {
      this.dialogFormVisible = true
      this.form = {}
    },
    save() { //保存信息
      this.dialogFormVisible = false
      this.request.post("/role/save", this.form).then(res => {
        if (res.code === '200') {
          this.$message.success("保存成功！")
          this.dialogFormVisible = false
        } else {
          this.$message.error("保存失败，请重试！")
        }
        this.load()
      })
    },
    handleEdit(row) { //修改信息
      this.form = row
      this.dialogFormVisible = true
    },
    deleteById(id) { //根据id删除用户
      console.log("要删除的id:" + id)
      this.request.delete("/role/" + id).then(res => {
        if (res.data) {
          this.$message.success("删除成功！")
          this.load()
        } else {
          this.$message.error("操作失败，请重试！")
        }
      })
    },
    handleSelectionChange(val) { //批量删除前的选择
      console.log(val) //val是一个数组对象，存放着每条记录的要展示的详细信息
      this.multipleSelection = val
    },
    isDelBatch() {
      this.dialogVisible = true
    },
    delBatch() { //批量删除
      let ids = this.multipleSelection.map(value => value.id) //从数组对象中获取到每一个的id项
      this.request.post("/role/del/batch", ids).then(res => {
        if (res.data) {
          this.$message.success("批量删除成功！")
          this.load()
        } else {
          this.$message.error("操作失败，请重试！")
        }
        this.dialogVisible = false
      })
    },
    async selectMenu(role) {
      this.roleId = role.id
      this.roleFlag = role.flag

      // 请求菜单数据
      this.request.get("/menu").then(res => {
        this.menuData = res.data
        // 把后台返回的菜单数据处理成 id数组
        this.expends = this.menuData.map(v => v.id)
      })

      this.request.get("/role/roleMenu/" + this.roleId).then(res => {
        this.checks = res.data
        this.ids.forEach(id => {
          if (!this.checks.includes(id)) {
            // 可能会报错：Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'setChecked')
            this.$nextTick(() => {
              this.$refs.tree.setChecked(id, false)
            })
          }
        })
        this.menuDialogVis = true
      })
    },
    saveRoleMenu() {
      this.request.post("/role/roleMenu/" + this.roleId, this.$refs.tree.getCheckedKeys()).then(res => {
        if (res.code === '200') {
          this.$message.success("绑定成功")
          this.menuDialogVis = false

          // 操作管理员角色后需要重新登录
          if (this.roleFlag === 'ROLE_ADMIN') {
            this.$store.commit("logout")
          }
        } else {
          this.$message.error(res.msg)
        }
      })
    }
  }
}
</script>

<style scoped>

</style>